<!DOCTYPE HTML>
<html lang="en">
<head>
  <meta charset="utf-8">

  <title>json&excel</title>
  <script src="./js/ace.js"></script>
  <script src="./js/jquery.js"></script>
  <script src="./js/FileSaver.min.js"></script>
  <script src="./js/xlsx.full.min.js"></script>
  <link href="./js/jsoneditor.min.css" rel="stylesheet" type="text/css">
  <script src="./js/jsoneditor-minimalist.js"></script>
<!--  <script src="./js/jsontoexcel.js"></script>-->
<!--  <script src="https://cuikangjie.github.io/JsonExportExcel/dist/JsonExportExcel.min.js"></script>-->
  <script src="./js/JsonExportExcel.min.js"></script>
  <style type="text/css">
    #jsoneditor {
      width: 800px;
      height: 500px;
      margin: 0 auto;
    }

    body, html {
      font-family: "DejaVu Sans", sans-serif;
    }

    p, li {
      width: 500px;
      font-size: 10.5pt;
    }

    code {
      background: #f5f5f5;
    }

    .main {
      text-align: center;
    }
  </style>
</head>
<body>
<div class="main">
  <div id="jsoneditor"></div>
  <div class="operator">
    <input id="filename" type="text" placeholder="请输入保存后的文件名">
    <button onclick="transferToExcelAndDownload()">转换为excel并下载</button>
    <button onclick="openJson()">打开json文件</button>
    <button onclick="getJsonAndDownload()">以json格式下载</button>
    <input id="file" type="file" hidden/>
    <button onclick="openExcelToJson()">打开excel转换为json</button>
  </div>
</div>
<script>
  // create the editor
  const container = document.getElementById('jsoneditor');
  const options = {
    modes: ['text', 'code', 'tree', 'form', 'view'],
    mode: 'code',
    ace: ace
  };
  const json = {
    string: 'hello world'
  };
  //editor用于设置编辑器的问本或得到文本
  const editor = new JSONEditor(container, options, json);
</script>
<script>
  /**
   * 打开文件，将值传入回调函数
   * @param func 带一个参数的回调函数
   * @param type json以编码utf8格式读取，excel以二进制读取
   */
  function openFile(func, type) {
    var file_btn = $("#file");
    file_btn.click();
    file_btn.change(function (evt) {
      if(evt.target.files.length <= 0){
        return;
      }
      var selectedFile = evt.target.files[0];
      var reader = new FileReader();
      reader.onload = function (event) {
        var data = event.target.result;
        var filename = selectedFile.name.split('.')[0];
        $("#filename").val(filename);
        func(data);
        file_btn.reset();
      };

      reader.onerror = function (event) {
        alert('读取出错！请重试！')
      };
      if(type == 'json'){
        reader.readAsText(selectedFile);
      }else if(type == 'excel'){
        reader.readAsBinaryString(selectedFile);
      }
    });
  }

  /**
   * 打开json文件并显示
   */
  function openJson() {
    openFile(function (data) {
      editor.setText(data);
    }, 'json');
  }

  /**
   * 将编辑的内容转换成excel文件并下载
   */
  function transferToExcelAndDownload() {
    var data = editor.getText();
    var jsonObj = JSON.parse(data);
    var keys = Object.keys(jsonObj);

    var option = {};
    var filename = $("#filename").val();
    if(filename == '' || filename == undefined){
      filename = 'config';
    }
    option.fileName = filename;
    option.datas = [
    ];

    for (var i = 0; i < keys.length; i++) {
      var key = keys[i];
      var val = jsonObj[key];
      var headers = [];
      if (Object.prototype.toString.call(val) === "[object Array]") {
        var valkeys = Object.keys(val[0]);
        for(var j = 0; j < valkeys.length; j++){
          headers.push(valkeys[j]);
        }
        option.datas.push({
          sheetData: val,
          sheetName: key,
          sheetHeader: headers
        });
      } else if (Object.prototype.toString.call(val) === '[object Object]') {
        var valkeys = Object.keys(val);
        for(var j = 0; j < valkeys.length; j++){
          headers.push(valkeys[j]);
        }
        option.datas.push({
          sheetData: [val],
          sheetName: key,
          sheetHeader: headers
        });
      }
    }

    var toExcel = new ExportJsonExcel(option);
    toExcel.saveExcel();
  }

  /**
   * 将正在编辑的json下载出来
   */
  function getJsonAndDownload() {
    var content = editor.getText();
    var blob = new Blob([JSON.stringify(JSON.parse(content))], {type: "text/plain;charset=utf-8"});
    var filename = $("#filename").val();
    if(filename == '' || filename == undefined){
      filename = 'config';
    }
    saveAs(blob, filename + ".json");//saveAs(blob,filename)
  }

  /**
   * 打开excel转换为json文件并显示
   */
  function openExcelToJson() {
    openFile(function (data) {
      var workbook = XLSX.read(data, {
        type: 'binary'
      });
      let ret = '{';
      workbook.SheetNames.forEach(function (sheetName) {
        var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
        var json_object = JSON.stringify(XL_row_object);
        ret += ('"' + sheetName + '":' + json_object + ',');
      });
      ret = ret.substring(0, ret.length - 1);
      ret += '}';
      editor.setText(ret);
    }, 'excel');
  }
</script>
</body>
</html>
